package com.raos.example.redis.networkmodel.reactor;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

/**
 * 单线程Reactor 模型（高性能I/O设计模式）
 * I/O 业务处理器
 *
 * @author raos
 * @emil 991207823@qq.com
 * @date 2021/7/23 23:32
 **/
public class Handler implements Runnable {

    /**
     * Socket信道
     */
    SocketChannel socketChannel;

    /**
     * 有参构造
     */
    public Handler(SocketChannel socketChannel) {
        this.socketChannel = socketChannel;
    }

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + "------");
        ByteBuffer buffer = ByteBuffer.allocate(1024);

        int len = 0, total = 0;
        String msg = "";
        try {
            do {
                len = socketChannel.read(buffer);
                if (len > 0) {
                    total += len;
                    msg += new String(buffer.array());
                }
            } while (len > buffer.capacity());

            System.out.println("接收字符长度: " + total);

            // msg=表示通信传输报文
            // 耗时2s
            // 登录： username: password
            // ServetRequets: 请求信息
            // 数据库的判断
            // 返回数据，通过channel写回到客户端

            System.out.println(socketChannel.getRemoteAddress() + " : Server receive Msg: " + msg);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (socketChannel != null) {
                try {
                    socketChannel.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
